var conn = MochiKit.Signal.connect;

/* http://www.dustindiaz.com/basement/block-toggle.html */
function switchMenu(obj, img) {
	var el = document.getElementById(obj);
	if ( el.style.display != "none" ) {
		el.style.display = 'none';
                document.getElementById(img).src = "/static/images/leftnav_bg_small.gif";
	}
	else {
		el.style.display = '';
                document.getElementById(img).src = "/static/images/leftnav_bg_expanded_small.gif";
	}
}

function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);


var PortletManager = {
    cookie_scope: '',
    expanded_portlets: [],

    readCookie: function() {
        // extract the expanded_portlets cookie
        // Code adapted from http://trac.mochikit.com/ticket/167
        var cookies = document.cookie;

        var prefix = 'expanded_portlets=';
        var begin = cookies.indexOf('; ' + prefix);
        if (begin == -1) {
            begin = cookies.indexOf(prefix);
            if (begin != 0) {
                // No cookie
                this.expanded_portlets = [];
                return;
            }
        } else {
            begin += 2;
        }
        var end = cookies.indexOf(';', begin);
        if (end == -1) {
            end = cookies.length;
        }
        var value = unescape(cookies.substring(begin + prefix.length, end));
        if (value) {
            this.expanded_portlets = value.split(',');
        } else {
            this.expanded_portlets = [];
        }
    },

    writeCookie: function() {
        var value = escape(this.expanded_portlets.join(','));
        var expire = new Date();
        // Keep the cookie for 31 days
        expire.setTime(expire.getTime() + 31 * 24 * 3600 * 1000);
        document.cookie = ('expanded_portlets=' + value )
        //+ '; Expires=' +
        //    expire.toGMTString() + this.cookie_scope);
    },

    shouldBeExpanded: function(portlet_id) {

        return findValue(this.expanded_portlets, portlet_id) >= 0;
    },

    togglePortlet: function(ev) {
        var portlet = getFirstParentByTagAndClassName(
            ev.src(), 'div', 'portlet');

        var is_expanded = hasElementClass(portlet, 'expanded');
        if (is_expanded) {
            swapElementClass(portlet, 'expanded', 'collapsed');


        } else {
            swapElementClass(portlet, 'collapsed', 'expanded');
            //portletbody[0].style.display = 'inline';//

        }
        is_expanded = !is_expanded;

        var portlet_id = getNodeAttribute(portlet, 'id');
        if (!portlet_id) {
            return;
        }
        var pos = findValue(this.expanded_portlets, portlet_id);
        var portletbody = getElement(portlet_id+'-body')
        var heading = getElement(portlet_id+'-h2')
        if (is_expanded && pos < 0) {
        	if (heading){
        	 setStyle(heading,{'background-image':'url(/static/images/leftnav_bg_expanded.gif)'})
        	}
        	showElement(portletbody)
            this.expanded_portlets.push(portlet_id);
            this.writeCookie()
        } else if (!is_expanded && pos >= 0) {
        	if (heading){
        	 setStyle(heading,{'background-image':'url(/static/images/leftnav_bg.gif)'})
        	}
        	hideElement(portletbody)
            this.expanded_portlets.splice(pos, 1);
            this.writeCookie()
        }
    },

    initialize: function(cookie_scope) {
        this.cookie_scope = cookie_scope;
        this.readCookie();
        var portlets_container = getElement('portlets');

        if (!portlets_container) {
            return;
        }
        var portlets = getElementsByTagAndClassName(
            'div', 'portlet', portlets_container);
        for (var i = 0; i < portlets.length; i++) {
            var portlet = portlets[i];

            var portlet_id = getNodeAttribute(portlet, 'id');
            var headings = getElementsByTagAndClassName('h2', null, portlet);
            // All portlets should have a heading, but check anyway to
            // avoid problems.
            if (portlet_id == 'actions' || headings.length == 0) {
                continue;
            }
            var heading = headings[0];
            if (portlet_id && this.shouldBeExpanded(portlet_id)) {
                portlet.className = 'portlet expanded';
                var portletbody = getElement(portlet_id+'-body')
                setStyle(heading,{'background-image':'url(/static/images/leftnav_bg_expanded.gif)'})
                showElement(portletbody)
            } else {
            	setStyle(heading,{'background-image':'url(/static/images/leftnav_bg.gif)'})
                portlet.className = 'portlet collapsed';
            }


            // Create an anchor to handle click-events, and reparent the
            // heading's children into it.  We do this rather than
            // connecting the event handler to the heading so that it
            // can be toggled with the keyboard.
            var anchor = document.createElement('a');
            anchor.href = 'javascript:undefined';
            while (heading.hasChildNodes()) {
                var child = heading.firstChild;
                heading.removeChild(child);
                anchor.appendChild(child);
            }
            heading.appendChild(anchor);
            connect(anchor, 'onclick', this, 'togglePortlet');
        }
    }
}

function toggleme(id){
        var div1 = document.getElementById(id)
        if (div1.style.display == 'none') {
                div1.style.display = 'block'
        } else {
                div1.style.display = 'none'
        }
}

var cookie_scope = '; Path=/; Secure; Domain=.launchpad.net';
function onLoadFunction() {
        PortletManager.initialize(cookie_scope);
      }



conn(window, 'onload', onLoadFunction);

